import pymysql
from settings import sql_settings

"""
封装数据库操作
"""


class MyMySQL:
    def __init__(self, host, user, password, database, port):
        try:
            self.con = pymysql.connect(
                host=host,
                user=user,
                password=password,
                database=database,
                port=port,
                charset="utf8",
                cursorclass=pymysql.cursors.DictCursor  # 以字典格式显示结果
            )
        except:
            raise

            # 创建游标
        self.cur = self.con.cursor()

    def get_result_from_database(self, sql, size=1):
        """
        获取查询结果列表
        :param sql: SQL语句
        :param size: 默认=1 查询一条，>1查询多条，-1查询所有
        :return: 查询结果
        """
        self.cur.execute(sql)

        if size == -1:
            return self.cur.fetchall()
        elif size == 1:
            return self.cur.fetchone()
        elif size > 1:
            return self.cur.fetchmany(size)

    def get_count_from_database(self, sql):
        """
        获取查询条数
        :param sql: SQL语句
        :return: 返回查询条数
        """
        count = self.cur.execute(sql)
        return count

    def update_sql(self, sql):
        """
        更新数据库
        :param sql: SQL语句
        :return: None
        """
        try:
            self.cur.execute(sql)
        except:
            self.con.rollback()
        self.con.commit()

    def close(self):
        self.cur.close()
        self.con.close()


if __name__ == '__main__':
    mysqlll = MyMySQL(**sql_settings)
    result = mysqlll.get_result_from_database("SELECT * FROM tz_user WHERE user_mobile=18572078726")
    print(result)
    mysqlll.close()
